<script lang="ts" setup>
import { onBeforeMount, reactive, ref,nextTick, watch, onBeforeUnmount, watchEffect } from "vue";

import { useDebouncedRef } from '@/utils/tools';
import md from '@/utils/markdown'
import { sendMessage, getChatMassageList, chatInfoData } from '@/api/chat'
import {useRoute} from 'vue-router'
import { userInfoStore } from "@/stores/userInfo";
import { ElNotification } from 'element-plus'
import ImgSys from '@/assets/img/logo1x.png'
import Interviews from "@/views/chat/functionTypeChat/interviews.vue";
import { log } from "console";
// import LoadingCp  from "@/components/loading/index.vue" 
// import { Loading } from "element-plus/es/components/loading/src/service.mjs";

// const messages = ref('') //普通的ref是直接触发更新
// const messages = useDebouncedRef('',1000)  //响应式防抖 这里没必要
const {userId,logo,} = userInfoStore().userInfo
const {token} = userInfoStore()
const route = useRoute()
// 历史聊天
const msgListArrHestry = ref([])

//是否显示聊天
const isdefinedChat = ref(false)
const typeChat = ref(1)
//会话窗口
const messages = reactive({
  id: route.query.chatId,
  question: '',
  userId
})

watch(() => messages.question,(newVal)=>{
  sendSteta.value = newVal.length < 1
})

// 控制发送按钮状态
const sendSteta = ref<boolean>(false)
//发送聊天消息 
const sendMessageAPI = async()=>{

  

  if (sendSteta.value){
    ElNotification({
      type: 'warning',
      message: '正在处理上一条信息请等待'
    })
    return
  }
  sendSteta.value = true //此时不能再发信息
  messages.id = route.query.chatId

  console.log(messages);
    // 发送消息
    let headers = {'Content-Type':'application/json'}
if(token){
  headers['Authorization'] = token
}

  let resizer = await fetch(import.meta.env.VITE_APP_URL + '/xlx-chat/chatMessage/sendMessage',{
  headers,
  method:'POST',
  body: JSON.stringify({
    id:messages.id,
    userId: messages.userId,
    question:messages.question
  })
})
  console.log('resizer',resizer);
  if (resizer.status !== 200){
    ElNotification({ type: 'warning', message: '发送失败' });
    sendSteta.value = false 
    return
  }
  const contentType = resizer.headers.get('Content-Type');
  // console.log('是不是流数据',contentType);
  if (contentType  ===  'application/json'){
    // console.log('不是流数据,但是拿不到返回的数据对象');
    const jsonResponse = await resizer.json();
    // console.log('解析到的数据:', jsonResponse);
    //
   ElNotification({
    type: 'warning',
    message: jsonResponse.errorMessage
   })
    sendSteta.value = false; //按钮状态
  }else{
    //添加本地用户对话信息
    ElNotification({
      type: 'success',
      message: '发送成功'
    })

    msgListArrHestry.value.push({
      role: 'user',
      content: messages.question
    })
    messages.question = ''
    // messages.question = ''
    //获取响应体的内容
    let reader = resizer.body?.getReader()
    console.log(reader);
    let decoder = new TextDecoder('utf-8')
    console.log('decoder', decoder);
    let len = msgListArrHestry.value.length
    msgListArrHestry.value[len] = {
      role: 'system',
      content: ''
    }
    //循环把流数据读完
    while (true) {
      const { done, value } = await reader.read() //我这里的流数据 也是read后拿到所有的吗  while 执行是在开始时 还是在 获取完成数据后？ 
      console.log(reader?.read());
      console.log(reader);
      console.log('value', value);

      //如果done 流数据完成
      if (done) {
        sendSteta.value = false;
        break
      }
      //  decoder 之后的数据
      const chunk = decoder.decode(value, { stream: true })
      try {
        const parseData = JSON.parse(chunk)
        //取出最终的content
        const { content } = parseData
        console.log(content);
        // 读到一起  加到聊天信息里面  防止重复添加
        msgListArrHestry.value[len].content += content.replace(msgListArrHestry.value[len].content, '')
        scrollToBottom() //下拉滚动
      } catch (e) {
        sendSteta.value = false
        console.log(e);
      }finally{
        sendSteta.value = false
      }
    }
  }



  }

// 滚动条向下
// 滚动到底
const chatContent = ref(null)
// 向下滚动
const scrollToBottom = ()=>{
  nextTick(()=>{
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight
    }
  }) //dom更新完成执行


const handleEnter = ()=>{
  console.log('回车发送请求');
}

// // 中文开始
// const handleStart = () => {
//   console.log('开始')
//   composing.value = true
// }
// // 中文结束
// const handleEnd = () => {
//   console.log('结束')
//   composing.value = false
// }

// interface ImsgListArrHestry {
//   role: string;
//   content: string;
//   userId: string
// }


//拿历史数据
}

const isLoding = ref(false)
const getHistoryData = async () => {
  // sendSteta.value = true; // 禁用发送按钮
  isLoding.value = true
  try {
    let res = await getChatMassageList({
      chatId:route.query.chatId
    })
    
    if (res.code === 0){
      console.log(res);
      msgListArrHestry.value = res.data
      isdefinedChat.value = true
      scrollToBottom() //向下滚动一次 
    }else{

    }
  } catch (error) {
    console.log(error);
  } finally{
    isLoding.value = false

  }
}

watch(() => route.query.chatId, (newValue) => {
  // console.log('newValue', newValue);
  if (newValue) {
    getHistoryData()  //信息列表    

      getChatInfoData() //面试信息详细
  }
})

onBeforeMount(() => {
  if (route.query.chatId){
    getHistoryData()
  }
})



// md
const markdown = (text:string)=>{
  return md.render(text)
}


//面试 查看备注的信息
const interViewInfo = ref({
  identity:'',
    occupation:'',
    isShow:false
})
const getChatInfoData =()=>{
  isLoding.value = true
  chatInfoData(route.query.chatId as string).then(
    (res) => {
      console.log(res);
      
      interViewInfo.value.identity = res.data.identity;
      interViewInfo.value.occupation = res.data.occupation;
      if (res.data.identity === null && res.data.question === '模拟面试'){
        interViewInfo.value.isShow = false
      }else{
        interViewInfo.value.isShow = true
      }
    },
      (rej) =>{
        console.log(rej);
      }
  ).finally(()=>{
    isLoding.value = false
  })
} 

//开始面试
const msgisShow = () => {
  interViewInfo.value.isShow = true
  getChatInfoData()
  getHistoryData()
}

</script>
<template>
  <div class="chatBox">

    <div class="loding" v-show=isLoding style="display: flex;background-color: rgb(242, 242, 242);height: 100%;
      ">
      <!-- <h3 style="text-align: center;"> 加载中后续整个图...</h3> -->
      <img v-if="isLoding" style="margin: auto;" src="@/assets/img/menu/loading.gif" alt="">
    </div>
    <Interviews v-if="!interViewInfo.isShow && route.meta.typeId === 2" @update="msgisShow"></Interviews>
    <div v-if="interViewInfo.isShow">
        <div class="chatData" v-if="isdefinedChat">
          <div class='interViewsInfo' v-if="route.meta.typeId === 2">
            <p>
              您选择的身份是:&nbsp;&nbsp;&nbsp; {{" "+ interViewInfo.identity +' '}}&nbsp;&nbsp; 面试岗位为:&nbsp;&nbsp;{{
              interViewInfo.occupation }}
            </p>
            <el-button @click='interViewInfo.isShow = false ;' type="primary" color='#c90000'>重新模型面试</el-button>
          </div>
          <ul class="chatList" ref="chatContent">
            <li v-for="item in msgListArrHestry" :key="item.id">
              <img :src="item.role === 'system' ? ImgSys : logo" alt=""></img>
              <div>
                <div v-if="item.role !== 'system'" class="rightUser">
                  {{ item.content }}
                </div>
                <!-- markdown -->
                <div v-else class="leftSys" v-html="markdown(item.content)"></div>
              </div>
            </li>
          </ul>
          <div class="send-chat-input">
            <!-- //这个可以正常输入 -->
            <textarea type="text" @keyup.enter="sendMessageAPI" v-model="messages.question" placeholder="请输入内容" />
            <!-- //这个element绑定的不会更新 每次只更新最后一次输入的值 -->
            <!-- <el-input v-model="messages" maxlength="3000" style="flex:1" type="textarea" placeholder="请输入内容" resize="none" /> -->
            <!-- {{ '有防抖会有延迟更新效果，' + messages }} -->
            <div class="sendBtn"
              :style="{ opacity: sendSteta ? 0.25 : 1, cursor: sendSteta ? 'not-allowed' : 'pointer' }"
              @click="sendMessageAPI">
              <img style="pointer-events: none;" src="@/assets/img/chat/sendmsg.png" alt="">
            </div>

            <!-- <el-button @click="sendMessage">sendMessage</el-button> -->
          </div>
        </div>


      </div>
    </div>
</template>

<style scoped lang='scss'>
.chatBox{
  position: relative;
  box-sizing: border-box;
  .loding{
    // position: absolute;
    // height: 100%;
    // align-items:center;
  }
.chatData{
    display: flex;
      flex-direction: column;
      height: calc(100vh - 36px);
      box-sizing: border-box;
      width: 100%;
.chatList{
  width: 100%;
  flex: 1;
  overflow-y: auto;
 box-sizing: border-box;
  li {
    display: flex;
    width: 100%;
    box-sizing: border-box;
    margin-top: 15px;
    padding: 0 5px;
    img{
      width: 40px;
      height: 40px;
      margin: 0 10px;
      border-radius: 50%;
    };
    div{
      padding: 13px 24px 26px 13px;
      border-radius: 5px;
      font-weight: 500;
    }
  }
}


.send-chat-input:focus-within {
  border-color: red;
  /* 当子元素获得焦点时，改变父元素的边框颜色 */
}

.send-chat-input {
  width: 100%;
  // height: 60px;
  display: flex;
  border: 1px transparent solid;
  transition: border .3s;
  box-sizing: border-box;
  align-items: center;
  background: #FFFFFF;

  textarea {
    height: 60px;
    font-size: 18px;
    flex: 1;
    box-sizing: border-box;
    padding: 10px 18px;
    outline: none;

  }

  .sendBtn {
    cursor: pointer;
    width: 50px;
    height: 50px;
    box-sizing: border-box;
    // background-color: #c90000;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-self: center;
    transition: background-color 1s;
    position: relative;
    &:hover {
 
      background-color: rgba($color: #c90000, $alpha: .4);
    }

    img {
        width: 20px;
        height: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%)

    }
  }
}
}
.leftSys{
  background: #FFFFFF;
}
.rightUser{
  background-color:rgb(245, 226, 221) ;
  font-size: 16px;
}
}

.interViewsInfo{
    background: #fff7f7;
    border-radius: 11px;
    border: 3px solid #c90000;
  display:flex;
  height:53px;
  align-items:center;
  // line-height : 53px;
      justify-content: space-between;
    padding: 0 8px;
  color:#c90000;
  font-weight:900;
  font-size:18px;
}


</style>
